package com.main.dao;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.main.pojo.ChartsDetail;
import com.main.pojo.TrollPhoto;
import com.main.pojo.Uploader;

@Transactional
@Repository
public class ChartsDAOImpl implements ChartsDAO {

	private SessionFactory sessionFactory;

	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<ChartsDetail> getCharts(String type, int topNumber) throws Exception{
		try {
			String hql = "SELECT c.id, c.troll.id, c.troll.title, c.troll.url, c.troll.viewNumber, c.troll.commentNumber, c.troll.uploader.id, " +
					"c.troll.uploader.name FROM ChartsDetail c WHERE c.charts.active = 'Y' and c.charts.chartsType = '" + type + "' ORDER BY c.total DESC";
			Query query = sessionFactory.getCurrentSession().createQuery(hql);
			query.setFirstResult(0);
			query.setMaxResults(topNumber);
			List<ChartsDetail> results = new ArrayList<ChartsDetail>();
			List<Object[]> ds =  query.list();
			if(ds != null){
				for (Object[] obj : ds) {
					ChartsDetail c = new ChartsDetail();
					TrollPhoto troll = new TrollPhoto();
					Uploader uploader = new Uploader();
					c.setId((Integer)obj[0]);
					troll.setId((Integer)obj[1]);
					troll.setTitle((String)obj[2]);
					troll.setUrl((String)obj[3]);
					troll.setViewNumber((Integer)obj[4]);
					troll.setCommentNumber((Integer)obj[5]);
					uploader.setId((Integer)obj[6]);
					uploader.setName((String)obj[7]);
					troll.setUploader(uploader);
					c.setTroll(troll);
					results.add(c);
				}
			}
			return results;
		} catch (Exception e) {
			throw e;
		}
	}

}
